﻿using Data;
using Services.Input;
using System;
using UnityEngine;

namespace Hero
{
    public class HeroReload : MonoBehaviour
    {
        public event Action Reloaded;

        public float Delay { get; set; }

        private PlayerControls _controls;
        private IInputService _inputService;
        private HeroState _state;
        private float _reload;
        private float _reloadTime = float.MinValue;

        public void Construct(IInputService inputService, HeroState state)
        {
            _inputService = inputService;
            _state = state;
            _controls = _inputService.GetControls();
            _controls.Enable();
        }

        private void Update()
        {
            _reload = _controls.Player.Reload.ReadValue<float>();

            if (_reload > 0)
                Reload();
        }

        public void ReplenishAmmo()
        {
            _state.ResetAmmo();
            Reloaded?.Invoke();
        }

        private void Reload()
        {
            if (Time.time < _reloadTime + Delay) return;

            _reload = 0;
            _reloadTime = Time.time;
            ReplenishAmmo();
        }
    }
}